package com.kunlun.common.utils;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 计算工具类
 *
 * GOOGLE 计算引擎 Aviator
 */
public class CalculateUtil {

    private static final Map<String, Expression> expMap = new HashMap<String, Expression>() {
        {
            put("a + b", AviatorEvaluator.compile("a + b"));
            put("a - b", AviatorEvaluator.compile("a - b"));
            put("a * b", AviatorEvaluator.compile("a * b"));
            put("a / b", AviatorEvaluator.compile("a / b"));
            put("a - b / c", AviatorEvaluator.compile("a - b / c"));
            put("(a - b) / c", AviatorEvaluator.compile("(a - b) / c"));
            put("a / b * c", AviatorEvaluator.compile("a / b * c"));
            put("a + b + c + d + e + f + g + h", AviatorEvaluator.compile("a + b + c + d + e + f + g + h"));
        }
    };

    public static String calculate(String expression, int scale, String ...args) {
        Expression exp = expMap.get(expression);
        if (null == exp) {
            expMap.put(expression, AviatorEvaluator.compile(expression));
        }

        Map<String, Object> variableMap = new HashMap<>();
        List<String> variableNames = exp.getVariableNames();
        for (int i = 0; i < variableNames.size(); i++) {
            variableMap.put(variableNames.get(i), null == args[i] ? BigDecimal.ZERO : new BigDecimal(args[i].toString()));
        }
        return formatScale(exp.execute(variableMap).toString(), scale);
    }

    public static String formatScale(String arg, int scale) {
        return new BigDecimal(arg).setScale(scale, BigDecimal.ROUND_HALF_UP).toPlainString();
    }
}
